

package com.maoshi.shop.coupon.comment.service.impl;

import java.util.Collections;
import java.util.Date;
import java.util.List;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.maoshi.shop.coupon.comment.dao.CouponUseRecordMapper;
import com.maoshi.shop.coupon.comment.dao.CouponUserMapper;
import com.maoshi.shop.coupon.comment.model.CouponUseRecord;
import com.maoshi.shop.coupon.comment.model.CouponUser;
import com.maoshi.shop.coupon.comment.service.CouponUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


/**
 * @author lgh on 2018/12/27.
 */
@Service
public class CouponUserServiceImpl extends ServiceImpl<CouponUserMapper, CouponUser> implements CouponUserService {

    @Autowired
    private CouponUserMapper couponUserMapper;

    @Autowired
    private CouponUseRecordMapper couponUseRecordMapper;

//    @Override
//    public List<CouponUser> getCouponAndCouponUserByCouponUserIds(List<Long> couponUserIds) {
//        if (CollectionUtil.isEmpty(couponUserIds)) {
//            return Collections.emptyList();
//        }
//        return couponUserMapper.getCouponAndCouponUserByCouponUserIds(couponUserIds);
//    }

    @Override
    public void deleteUnValidTimeCoupons(Date date) {
        couponUserMapper.deleteUnValidTimeCoupons(date);
    }

    @Override
    public void updateStatusByTime(Date now) {
        couponUserMapper.updateStatusByTime(now);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelOrder(String userId, String orderNumber) {

        //查询订单所使用的优惠券列表
        List<CouponUseRecord> couponUseRecordList = couponUseRecordMapper.selectList(new LambdaQueryWrapper<CouponUseRecord>()
                .eq(CouponUseRecord::getUserId, userId)
                .eq(CouponUseRecord::getOrderNumber, orderNumber));
        if (CollectionUtils.isEmpty(couponUseRecordList)) {
            return;
        }
        List<Long> couponUseRecordIdList = Lists.newArrayList();
        List<Long> couponUserIds = Lists.newArrayList();
        for (CouponUseRecord couponUseRecord : couponUseRecordList) {
            couponUseRecordIdList.add(couponUseRecord.getCouponUseRecordId());
            couponUserIds.add(couponUseRecord.getCouponUserId());
        }

        //删除优惠券使用记录
        couponUseRecordMapper.deleteBatchIds(couponUseRecordIdList);

        //修改用户优惠券状态为可用状态
        couponUserMapper.batchUpdateUserCouponStatus(1, couponUserIds);
    }

}
